package Servlet;

import Dao.BillDao;
import Model.Bill;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;

@WebServlet("/AiServlet")
public class AiServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.print("dogged");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 从请求中解析前端传入的 imageUrl
            StringBuilder requestBody = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
            JSONObject requestJson = new JSONObject(requestBody.toString());
            String imageUrl = requestJson.getString("imageUrl");

            // 调用多模态对话 API
            String result = simpleMultiModalConversationCall(imageUrl);

            // 提取信息
            String dateTime = extractValue(result, "日期：(\\d{4}年\\d{2}月\\d{2}日)");
            String itemName = extractValue(result, "购买物品名称：(.+)");
            String seller = extractValue(result, "卖方：(.+)");
            String purchaser = extractValue(result, "买方：(.+)");
            String amountStr = extractValue(result, "金额：([\\d.]+)元");

            // 转换日期格式
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
            LocalDate date = LocalDate.parse(dateTime, inputFormatter);
            String formattedDate = date.toString(); // 格式为 YYYY-MM-DD

            // 清洗金额字符串，去除货币单位
            amountStr = amountStr.replace("元", "").trim();
            BigDecimal money = new BigDecimal(amountStr);

            // 获取用户ID
            HttpSession session = request.getSession(false);
            int userID = (Integer) session.getAttribute("UserID");
            int id = BillDao.selectNewID();

            // 创建并插入账单
            Bill bill = new Bill(id, userID, formattedDate, imageUrl, itemName, seller, purchaser, money);
            BillDao.insert(bill);

            // 返回结果
            out.print(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage());
            out.print(errorResponse.toString());
        } catch (Exception e) {
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("status", "error");
            errorResponse.put("message", "未知错误: " + e.getMessage());
            out.print(errorResponse.toString());
        } finally {
            out.flush();
            out.close();
        }
    }

    private String extractValue(String input, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            return matcher.group(1); // 返回匹配到的值
        } else {
            return "未找到匹配项"; // 提供默认值或记录错误
        }
    }

    private String simpleMultiModalConversationCall(String imageUrl) throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("text", "You are a helpful assistant."))).build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", imageUrl),
                        Collections.singletonMap("text", "整理这张发票的日期、购买物品名称、卖方、买方以及金额，并规范化你的格式，不要有多余的符号，无需统一社会信用代码/纳税人识别号，金额统一用元作为后缀"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(System.getenv("sk-5019fa9093804345a57078be7b9d3031"))
                .model("qwen-vl-max-latest")
                .messages(Arrays.asList(systemMessage, userMessage))
                .build();
        MultiModalConversationResult result = conv.call(param);

        // 检查返回结果是否有效
        if (result.getOutput() != null && result.getOutput().getChoices() != null && !result.getOutput().getChoices().isEmpty()) {
            var choice = result.getOutput().getChoices().get(0);
            if (choice.getMessage() != null && choice.getMessage().getContent() != null && !choice.getMessage().getContent().isEmpty()) {
                // 安全地获取并转换文本内容
                Object textObject = choice.getMessage().getContent().get(0).get("text");
                if (textObject instanceof String) {
                    return (String) textObject;
                } else {
                    return "Invalid response format.";
                }
            }
        }

        // 如果结果无效，返回默认错误提示
        return "未获取到有效的响应结果。";
    }


}